<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.example.dao.CartDao" %>
<%@ page import="com.example.domain.CartWithProduct" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="com.example.dao.ProductDao" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.domain.Order" %>
<%@ page import="com.example.dao.OrderDao" %>
<%@ page import="com.example.domain.OrderItem" %>
<%@ page import="com.example.domain.Product" %>
<%@ page import="java.util.Optional" %>
<%@ page import="java.sql.SQLException" %>
<%!

    // 生成订单号的方法
    private String generateOrderNo() {
        // 使用当前时间戳+随机数生成订单号
        long timestamp = System.currentTimeMillis();
        int randomNum = (int) (Math.random() * 9000) + 1000; // 生成4位随机数
        return "ORD" + timestamp + randomNum;
    }
%>
<%
    // 检查用户是否已登录
    User currentUser = (User) session.getAttribute("user");
    if (currentUser == null) {
        response.sendRedirect("../auth/login.jsp");
        return;
    }

    // 获取选中的商品ID
    String[] selectedProductIds = request.getParameterValues("selectedItems");
    if (selectedProductIds == null || selectedProductIds.length == 0) {
        response.sendRedirect("../view/cart.jsp");
        return;
    }

    // 转换为整数数组
    List<Integer> productIdList = new ArrayList<>();
    for (String id : selectedProductIds) {
        productIdList.add(Integer.parseInt(id));
    }

    Connection conn = null;
    double totalAmount = 0;
    int productCount = 0;
    List<CartWithProduct> selectedItems = new ArrayList<>();
    int orderId = -1;
    
    try {
        conn = DBUtil.getConnection();
        conn.setAutoCommit(false); // 开启事务
        
        CartDao cartDao = new CartDao();
        ProductDao productDao = new ProductDao();
        
        // 获取用户购物车中的选中商品
        List<CartWithProduct> cartItems = cartDao.getCartListByMemberId(currentUser.getId());
        
        for (CartWithProduct item : cartItems) {
            if (productIdList.contains(item.getProduct_id())) {
                selectedItems.add(item);
                totalAmount += item.getSale_money();
                productCount += item.getSale_num();
            }
        }
        
        if (!selectedItems.isEmpty()) {
            // 生成订单号
            String orderNo = generateOrderNo();
            
            // 创建订单对象
            Order order = new Order();
            order.setOrder_no(orderNo);
            order.setUser_id(currentUser.getId());
            order.setTotal_amount(totalAmount);
            order.setProduct_count(productCount);
            order.setStatus(0); // 设置为待支付
            order.setReceiver_name(currentUser.getUsername());
            order.setReceiver_phone(currentUser.getPhone() != null ? currentUser.getPhone() : "");
            order.setReceiver_address(currentUser.getAddress() != null && !currentUser.getAddress().isEmpty() ? currentUser.getAddress() : "暂无地址信息，请到个人中心完善");
            
            // 使用OrderDao创建订单
            OrderDao orderDao = new OrderDao();
            orderId = orderDao.createOrder(order);
            
            if (orderId != -1) {
                // 创建订单项并从购物车中删除商品
                for (CartWithProduct item : selectedItems) {
                    // 获取商品名称
                    Optional<Product> productOpt = productDao.getProductById(item.getProduct_id());
                    String productName = productOpt.isPresent() ? productOpt.get().getProduct_name() : "未知商品";
                    
                    // 创建订单项对象
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrder_id(orderId);
                    orderItem.setProduct_id(item.getProduct_id());
                    orderItem.setProduct_name(productName);
                    orderItem.setPrice(item.getSale_price());
                    orderItem.setQuantity(item.getSale_num());
                    orderItem.setSubtotal(item.getSale_money());
                    
                    // 添加到订单项表
                    orderDao.createOrderItem(orderItem);
                    
                    // 从购物车中删除
                    cartDao.removeProductFromCart(currentUser.getId(), item.getProduct_id());
                }
                
                conn.commit(); // 提交事务
            }
        }
        
    } catch (Exception e) {
        if (conn != null) {
            try {
                conn.rollback(); // 回滚事务
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        e.printStackTrace();
        response.getWriter().println("{\"success\": false, \"message\": \"订单处理失败: " + e.getMessage() + "\"}");
        return;
    } finally {
        if (conn != null) {
            try {
                conn.setAutoCommit(true);
                conn.close();
            } catch (Exception e) {
                // 忽略关闭连接的异常
            }
        }
    }
    
    if (orderId != -1) {
        session.setAttribute("orderId", orderId);
        response.getWriter().println("{\"success\": true, \"message\": \"订单创建成功\", \"orderId\": " + orderId + "}");
    } else {
        response.getWriter().println("{\"success\": false, \"message\": \"创建订单失败\"}");
    }
%>